package cn.com.idmy.auth.oauth;

import cn.com.idmy.auth.context.Request;
import cn.com.idmy.auth.context.Response;
import cn.com.idmy.auth.token.TokenConfigDao;
import cn.com.idmy.auth.token.jwt.JwtTokenManager;
import cn.com.idmy.base.util.Assert;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.dromara.hutool.core.codec.binary.Base64;
import org.dromara.hutool.core.lang.tuple.Pair;
import org.dromara.hutool.core.text.StrUtil;
import org.jetbrains.annotations.NotNull;

@Setter
@Accessors(fluent = true)
public abstract class AbstractAccessToken<ID> {
    private static final String BASIC = "Basic ";
    protected OauthManager<ID> oauthManager;
    protected TokenConfigDao<ID> tokenConfigDao;
    protected JwtTokenManager<ID> jwtTokenManager;

    protected abstract @NotNull AccessToken getToken(@NotNull Request request, @NotNull Response response);

    protected Pair<String, String> getClientInfoFromAuthorization(String auth) {
        var authorization = Assert.notBlank(auth, "authorization 不能为空");
        var removed = StrUtil.removePrefix(authorization, BASIC);
        var pair = Assert.notBlank(Base64.decodeStr(removed), "clientId 和 clientSecret 不能为空");
        var arr = pair.split(":");
        var clientId = Assert.notBlank(arr[0], "clientId 不能为空");
        if (arr.length == 2) {
            var clientSecret = arr[1];
            return new Pair<>(clientId, clientSecret);
        } else {
            return new Pair<>(clientId, null);
        }
    }
}
